/**
 * 
 */
package com.numericme.locale.switcher;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.numericme.locale.switcher.tools.ProMode;
import com.numericme.locale.switcher.tools.Tools;

/**
 * The settings activity.
 * 
 * @author NumericMe
 */
public class SettingsActivity extends PreferenceActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {

	private SharedPreferences prefs;

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	@Override
	protected void onStop() {
		prefs.unregisterOnSharedPreferenceChangeListener(this);
		super.onStop();
	}	

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		String preftoUse = Tools.SHARED_PREFS_NAME;		
		getPreferenceManager().setSharedPreferencesName(preftoUse);
		
		prefs = getPreferenceManager().getSharedPreferences();
		prefs.registerOnSharedPreferenceChangeListener(this);

		if (ProMode.isInProMode(this)) {
			addPreferencesFromResource(R.xml.settings);
		}
		else{
			addPreferencesFromResource(R.xml.settings_ads);
		}
		
		//Get prefSreens
		PreferenceScreen aboutPrefScreen = (PreferenceScreen) getPreferenceScreen().findPreference(Tools.ABOUT_PREF_SCREEN);

		//Get prefCategories
		PreferenceCategory toolsSettingsCat = (PreferenceCategory) getPreferenceScreen().findPreference(Tools.TOOLS_SETTINGS_CAT);
		PreferenceCategory notificationsSettingsCat = (PreferenceCategory) getPreferenceScreen().findPreference(Tools.NOTIFICATIONS_SETTINGS_CAT);

		//All prefScreens with R.drawable.background!
		try{
			getWindow().setBackgroundDrawableResource(R.drawable.background);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			aboutPrefScreen.setOnPreferenceClickListener(new OnPreferenceClickListener() {
				public boolean onPreferenceClick(Preference preference) {
					PreferenceScreen a = (PreferenceScreen) preference;
					a.getDialog().getWindow().setBackgroundDrawableResource(R.drawable.background);	     
					a.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
					return true;
				}
			});
		}
		catch(OutOfMemoryError e){	    	
		}		
		
		aboutPrefScreen.setTitle(R.string.about_pref_screen_title);

		
		//Preferences added from code
		CheckBoxPreference localeSwitcher = new CheckBoxPreference(this);
		localeSwitcher.setKey(Tools.LOCALE_SWITCHER_KEY);
		localeSwitcher.setDefaultValue(Boolean.parseBoolean(getString(R.string.locale_switcher_pref_def_value)));
		localeSwitcher.setTitle(R.string.locale_switcher_pref);
		localeSwitcher.setSummaryOn(R.string.tool_pref_summaryOn);
		localeSwitcher.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(localeSwitcher);

		CheckBoxPreference rotation = new CheckBoxPreference(this);
		rotation.setKey(Tools.ROTATION_KEY);
		rotation.setDefaultValue(Boolean.parseBoolean(getString(R.string.rotation_pref_def_value)));
		rotation.setTitle(R.string.rotation_pref);
		rotation.setSummaryOn(getString(R.string.tool_pref_summaryOn) + " " + getString(R.string.rotation_pref_sumOn));
		rotation.setSummaryOff(getString(R.string.tool_pref_summaryOff) + " " + getString(R.string.rotation_pref_sumOn));
		toolsSettingsCat.addPreference(rotation);

		CheckBoxPreference wifi = new CheckBoxPreference(this);
		wifi.setKey(Tools.WIFI_KEY);
		wifi.setDefaultValue(Boolean.parseBoolean(getString(R.string.wifi_pref_def_value)));
		wifi.setTitle(R.string.wifi_pref);
		wifi.setSummaryOn(R.string.tool_pref_summaryOn);
		wifi.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(wifi);
		
		CheckBoxPreference display = new CheckBoxPreference(this);
		display.setKey(Tools.DISPLAY_KEY);
		display.setDefaultValue(Boolean.parseBoolean(getString(R.string.display_pref_def_value)));
		display.setTitle(R.string.display_pref);
		display.setSummaryOn(R.string.tool_pref_summaryOn);
		display.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(display);
		
		CheckBoxPreference sound = new CheckBoxPreference(this);
		sound.setKey(Tools.SOUND_KEY);
		sound.setDefaultValue(Boolean.parseBoolean(getString(R.string.sound_pref_def_value)));
		sound.setTitle(R.string.sound_pref);
		sound.setSummaryOn(R.string.tool_pref_summaryOn);
		sound.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(sound);
		
		CheckBoxPreference systemSettings = new CheckBoxPreference(this);
		systemSettings.setKey(Tools.SYSTEM_SETTINGS_KEY);
		systemSettings.setDefaultValue(Boolean.parseBoolean(getString(R.string.system_settings_pref_def_value)));
		systemSettings.setTitle(R.string.system_settings_pref);
		systemSettings.setSummaryOn(R.string.tool_pref_summaryOn);
		systemSettings.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(systemSettings);
		
		CheckBoxPreference instantToolsSettings = new CheckBoxPreference(this);
		instantToolsSettings.setKey(Tools.INSTANT_TOOLS_PREFERENCES_KEY);
		instantToolsSettings.setDefaultValue(Boolean.parseBoolean(getString(R.string.instant_tools_preferences_pref_def_value)));
		instantToolsSettings.setTitle(R.string.instant_tools_preferences_pref);
		instantToolsSettings.setSummaryOn(R.string.tool_pref_summaryOn);
		instantToolsSettings.setSummaryOff(R.string.tool_pref_summaryOff);
		toolsSettingsCat.addPreference(instantToolsSettings);
				
		CheckBoxPreference invisibleNotifications = new CheckBoxPreference(this);
		invisibleNotifications.setKey(Tools.INVISIBLE_NOTIFICATIONS_KEY);
		invisibleNotifications.setDefaultValue(false);
		invisibleNotifications.setTitle(R.string.invisible_notifications_pref);
		invisibleNotifications.setSummaryOn(R.string.invisible_notifications_pref_summaryOn);
		invisibleNotifications.setSummaryOff(R.string.invisible_notifications_pref_summaryOff);
		notificationsSettingsCat.addPreference(invisibleNotifications);

		CheckBoxPreference autoActivateOnBoot = new CheckBoxPreference(this);
		autoActivateOnBoot.setKey(Tools.AUTO_ACTIVATE_ON_BOOT_KEY);
		autoActivateOnBoot.setDefaultValue(true);
		autoActivateOnBoot.setTitle(R.string.auto_activate_on_boot_pref);
		autoActivateOnBoot.setSummaryOn(R.string.auto_activate_on_boot_pref_summaryOn);
		autoActivateOnBoot.setSummaryOff(R.string.auto_activate_on_boot_pref_summaryOff);
		notificationsSettingsCat.addPreference(autoActivateOnBoot);
		
		//Other prefs		
		final String version = Tools.getVersionName(this,SettingsActivity.class);
		Preference changeLogDialog = new Preference(this);
		changeLogDialog.setKey(Tools.PREF_CHANGE_LOG);
		changeLogDialog.setTitle(getString(R.string.pref_change_log_title) + version);
		changeLogDialog.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {			
			public boolean onPreferenceClick(Preference preference) {
				showCustomDialog(getString(R.string.pref_change_log_title) + version,getString(R.string.change_log_msg),android.R.drawable.ic_menu_help);
				return true;
			}
		});
		aboutPrefScreen.addPreference(changeLogDialog);

		Preference termsOfUseDialog = new Preference(this);
		termsOfUseDialog.setTitle(R.string.terms_of_use_title);
		termsOfUseDialog.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {			
			public boolean onPreferenceClick(Preference preference) {
				showCustomDialog(getString(R.string.terms_of_use_title),getString(R.string.terms_of_use_msg),android.R.drawable.ic_menu_help);
				return true;
			}
		});
		aboutPrefScreen.addPreference(termsOfUseDialog);
		
		if (!ProMode.isInProMode(this)) {
			Preference upgPreference = new Preference(
					this);
			upgPreference.setTitle(getString(R.string.get_pro_app_title));
			upgPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {				
				public boolean onPreferenceClick(Preference preference) {
					GetProKey();
					return true;
				}
			});
			aboutPrefScreen.addPreference(upgPreference);
		}
		
		//Initialize the starting preferences
		onSharedPreferenceChanged(prefs,Tools.SETTINGSACTIVITY_INIT);		
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String keyChanged) {
		//List preferences summary updates
		if (keyChanged.startsWith(Tools.LIST_PREF_PREFIX)) {
			ListPreference test = new ListPreference(this);
			test = (ListPreference) this.findPreference(keyChanged);
			if (test.getEntry() != null)
				test.setSummary(test.getEntry());
		}
		
		if(keyChanged.equals(Tools.INVISIBLE_NOTIFICATIONS_KEY)){
			Tools.cancelNotifications(this);
			Tools.displayNotification(this, sharedPrefs.getBoolean(Tools.INVISIBLE_NOTIFICATIONS_KEY, Boolean.parseBoolean(getString(R.string.invisible_notifications_pref_def_value))));	
		}
	}

	private void showCustomDialog(String string, CharSequence msg, int icon) {
		//Custom alert dialog
		AlertDialog checkInstallDialog;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.custom_dialog,(ViewGroup) findViewById(R.id.layout_root));

		TextView text_1 = (TextView) layout.findViewById(R.id.text_1);
		text_1.setText(msg);

		builder.setView(layout);			
		builder.setTitle(string);
		builder.setIcon(icon);
		builder.setCancelable(false);
		builder.setPositiveButton(
				getString(R.string.tutorial_dialog_btn_ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		checkInstallDialog = builder.create();
		try {
			checkInstallDialog.show();
		}
		catch(OutOfMemoryError e){
		}		
	}
	
	private void GetProKey() {
		Uri marketUri = Uri.parse("market://details?id="
				+ Tools.PACKAGE_NAME + ".full");
		launchMarket(marketUri);
	}
	
	private void launchMarket(Uri marketUri) {
		try {
			this.startActivity(new Intent(Intent.ACTION_VIEW)
					.setData(marketUri));
		} catch (ActivityNotFoundException e) {
		}	
	}
}